<?php

namespace app\api\controller\user;

use app\api\controller\Controllers;
use app\api\service\user\OAuth2 as OAuth2Service;
use app\api\service\user\UserNumber;
use app\api\service\user\UserInfo;
use other\Token;

class OAuth2 extends Controllers
{

    /**
     * 第三方登录
     * @param OAuth2Service $service
     * @param UserNumber $userNumber
     * @return \think\Response
     */
    public function login( OAuth2Service $service, UserNumber $userNumber )
    {
        $get = $this->request->only(['code','state'], 'get');
        $this->validate($get, 'app\api\validate\user\OAuth2.oauto2');
        $user = $service->handle($get['code'], $get['state']);
        // 注册或登录
        return success([
            'token' => Token::encode($userNumber->reg($user['openid'], $get['state']))
        ]);
    }

    /**
     * 添加用户信息
     *
     * @return \think\Response
     */
    public function addInfo( UserInfo $userInfo )
    {
        $post  = $this->request->only(['nickname','head_url','gender','country','province','city','lat','lon'], 'post');
        $this->validate($post, 'app\api\validate\user\UserInfo');
        return $userInfo->saveUserInfo($post)?
            success():
            failed('用户信息插入失败');
    }

}
